<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :search.sync="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.remainMedicine_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出
        </el-button>
      </template>

    </avue-crud>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove} from "@/api/business/remainMedicine";
import {mapGetters} from "vuex";
import {getBatchList} from "@/api/business/batchOrderItem";
import {exportBusinessMonth} from "@/api/business/purchaseItem";
import NProgress from "nprogress";
import {exportBlob} from "@/api/common";
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";
import {dateNow} from "@/util/date";
import func from "@/util/func";


export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      search: {},
      selectionList: [],
      option: {
        searchLabelWidth: 100,
        searchGutter: 0,
        searchSpan: 6,
        menuWidth: 80,
        columnBtn: false,
        editBtn: true,
        excelBtn: true,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        menu: true,
        border: true,
        viewBtn: true,
        dialogClickModal: false,
        dialogWidth: '60%',
        column: [
          {
            label: "id",
            prop: "id",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "批次",
            prop: "batchId",
            type: "select",
            dicData: [],
            props: {
              label: "batchName",
              value: "id"
            },
            width: 150,
            labelWidth: 100,
            searchLabelWidth: 60,
            editDisplay: false,
            search: true,
            hide: true,
          },
          {
            label: "批次名称",
            prop: "batchName",
            type: "input",
            width: 130,
            overHidden: true,
            labelWidth: 100,
            editDisplay: false,
          },
          {
            label: "医药机构id",
            prop: "instId",
            type: "input",
            addDisplay: false,
            hide: true,
            viewDisplay: false,
            editDisabled: true,
            editDisplay: false,
            labelWidth: 200,
          },
          {
            label: "医药机构名称",
            prop: "instName",
            type: "input",
            width: 130,
            overHidden: true,
            //hide: true,
            search: true,
            editDisplay: false,
            addDisplay: false,
            editDisabled: true,
            labelWidth: 200,
          },
          {
            label: "区县",
            prop: "district",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=medpur_institution",
            dataType: "number",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: true,
            //hide: true,
            searchLabelWidth: 60,
            addDisplay: false,
            editDisplay: false,
            editDisabled: true
          },
          {
            label: "年度",
            prop: "year",
            type: "year",
            format: "yyyy",
            valueFormat: "yyyy",
            search: true,
            hide: true,
            searchLabelWidth: 60,
            editDisplay: false,
          },
          {
            label: "药品流水号",
            prop: "medicineNo",
            type: "input",
            editDisplay: false,
            width: 100,
            labelWidth: 200,
          },
          {
            label: "药品通用名",
            prop: "medicineName",
            type: "input",
            search: true,
            overHidden: true,
            editDisplay: false,
            width: 130,
            labelWidth: 200,
          },
          {
            label: "规格",
            prop: "specification",
            type: "input",
            editDisplay: false,
          },
          {
            label: "包装",
            prop: "packages",
            type: "input",
            editDisplay: false,
          },
          {
            label: "计价单位",
            prop: "chargeUnit",
            type: "input",
            editDisplay: false,
          },
          {
            label: "约定采购量基数",
            prop: "purchaseBasicNumber",
            type: "input",
            width: 110,
            labelWidth: 200,
            editDisplay: false,
          },
          {
            label: "加权平均价格",
            prop: "avgPrice",
            type: "input",
            width: 100,
            editDisplay: false,
            labelWidth: 200,
          },
          {
            label: "中选产品约定量",
            prop: "promiseAmount",
            type: "input",
            editDisplay: false,
            width: 120,
            labelWidth: 200,
          },
          {
            label: "非中选产品使用金额",
            prop: "unelectedUseFee",
            type: "input",
            editDisplay: false,
            width: 130,
            labelWidth: 200,
          },
          {
            label: "上年度全院总用量",
            prop: "lastyearInstTotal",
            type: "input",
            editDisplay: false,
            width: 130,
            labelWidth: 200,
          },
          {
            label: "上年度全院参保患者使用量",
            prop: "lastyearSecurityUserTotal",
            type: "input",
            width: 170,
            labelWidth: 200,
            editDisplay: false,
          },
          {
            label: "中选价格",
            prop: "electedPrice",
            type: "input",
            editDisplay: false,
          },
          {
            label: "参保患者使用量占比",
            prop: "securityUserRatio",
            type: "input",
            width: 150,
            labelWidth: 200,
            // hide: true,
            rules: [{
              required: true,
              message: "请输入参保患者使用量占比（小数）",
              trigger: "blur",
              pattern: /^[0-9]+(\.[0-9]+)?$/,
            }],
            addDisplay: false,
            viewDisplay: false,
            editDisplay: true,
          },
          {
            label: "上年度实际支付比例",
            prop: "lastyearActualPayRatio",
            type: "input",
            addDisplay: false,
            width: 150,
            // hide: true,
            rules: [{
              required: true,
              message: "请输入实际支付比例（小数）",
              trigger: "blur",
              pattern: /^[0-9]+(\.[0-9]+)?$/,
            }],
            viewDisplay: false,
            editDisplay: true,
            labelWidth: 200,
          },
          {
            label: "结余留用比例",
            prop: "remainRatio",
            type: "input",
            width: 100,
            rules: [{
              required: true,
              message: "请输入结余留用比例（小数）",
              trigger: "blur",
              pattern: /^[0-9]+(\.[0-9]+)?$/,
            }],
            // hide: true,
            addDisplay: false,
            viewDisplay: false,
            editDisplay: true,
            labelWidth: 200,
          },
          {
            label: "考核拨付比例",
            prop: "examineAppropriateRatio",
            type: "input",
            width: 100,
            addDisplay: false,
            //hide: true,
            rules: [{
              required: true,
              message: "请输入考核拨付比例（小数）",
              trigger: "blur",
              pattern: /^[0-9]+(\.[0-9]+)?$/,
            }],
            viewDisplay: false,
            editDisplay: true,
            labelWidth: 200,
          },
          {
            label: "医保资金预算",
            prop: "securityBudget",
            type: "input",
            editDisplay: false,
            width: 100,
            labelWidth: 200,
          },
          {
            label: "结余测算基数",
            prop: "remainEstimateBasic",
            type: "input",
            width: 100,
            //  hide: true,
            editDisplay: false,
            addDisplay: false,
            labelWidth: 200,
          },
          {
            label: "结余留用金额",
            prop: "remainFee",
            type: "input",
            width: 100,
            //hide: true,
            editDisplay: false,
            addDisplay: false,
            labelWidth: 200,
          },

        ]
      },
      data: []
    };
  },
  created() {
    console.log("role_name", this.userInfo.role_name);
    getBatchList().then(res => {
      this.findObject(this.option.column, "batchId").dicData = res.data.data;
    });
  },
  computed: {
    ...mapGetters(["userInfo", "permission", "loginUserInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.remainMedicine_add, false),
        viewBtn: this.vaildData(this.permission.remainMedicine_view, false),
        delBtn: this.vaildData(this.permission.remainMedicine_delete, false),
        editBtn: this.vaildData(this.permission.remainMedicine_edit, true)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    handleExport() {
      const batchId = func.toStr(this.search.batchId);
      const district = func.toStr(this.search.district);
      const year = func.toStr(this.search.year);
      const medicineName = func.toStr(this.search.medicineName);
      const instName = func.toStr(this.search.instName);

      this.$confirm("是否导出药品数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          NProgress.start();
          exportBlob(`/api/remainMedicine/exportMedicine?${this.website.tokenHeader}=${getToken()}&batchId=${batchId}&district=${district}&year=${year}&medicineName=${medicineName}&instName=${instName}`).then(res => {
            downloadXls(res.data, `药品结余留用统计数据${dateNow()}.xlsx`);
            NProgress.done();
          })
        }
      );
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      if(this.userInfo.role_name.includes('districtAdmin')){
        this.option.menu=false;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style>
</style>
